'use strict';
/**
 * @fileoverview 联盟任务系统
 * @author sundbcn@gmail.com (sun debing)
 */

var mongoose = require('mongoose');
var moment = require('moment');
var _ = require('lodash');
var constantUtil = require('../../util/constantUtil.js');
var unionTaskMgr = require('../../mgr/unionTaskMgr.js');
var dataApi = require('../../libs/dataApi');
var unionMissionConf = require('../../config/unionMissionConf.js');
var ObjectId = mongoose.Types.ObjectId;

var _unionTime = function () {
    return moment().unix();
};

var _unionTask = function () {
    var unionTask_list = [];
    var task_list = unionMissionConf.randomReward();
    _.each(task_list, function (item) {
        unionTask_list.push({
            task_id: item.id,
            cost_time: item.cost_time,
            end_time: 0,
            star: item.star,
            reputation: item.reputation,
            _id: new ObjectId()
        });
    });
    return unionTask_list;
};
///////////////////////////////////////////////////////////
/**
 * 联盟任务系统子项
 * @type {mongoose}
 */
var unionTaskItemSchema = new mongoose.Schema({

    // 任务id
    task_id: {
        type: Number,
        default: 0
    },

    // 任务完成需要时间
    cost_time: {
        type: Number,
        default: 0
    },

    // 任务完成星数
    star: {
        type: Number,
        default: 0
    },

    // 任务完成星数
    reputation: {
        type: Number,
        default: 0
    },

    // 任务结束时间
    end_time: {
        type: Number,
        default: 0
    }
});

if (!unionTaskItemSchema.options.toJSON) {
    unionTaskItemSchema.options.toJSON = {};
}

/* jshint unused:false */
unionTaskItemSchema.options.toJSON.transform = function (doc, ret) {
    delete ret._id;
    delete ret.__v;
};

///////////////////////////////////////////////////////////

/**
 * 联盟捐赠子项
 * @type {mongoose}
 */
var unionDonatedItemSchema = new mongoose.Schema({

    // 三个按妞类型  1，2，3
    donated_type: {
        type: Number,
        default: 0
    },

    // 奖励类型
    reward_type: {
        type: Number,
        default: 0
    },

    // 奖励数量
    reward_num: {
        type: Number,
        default: 0
    },

    // 是否开启
    is_open: {
        type: Number,
        default: 0
    }
});

if (!unionDonatedItemSchema.options.toJSON) {
    unionDonatedItemSchema.options.toJSON = {};
}

/* jshint unused:false */
unionDonatedItemSchema.options.toJSON.transform = function (doc, ret) {
    delete ret._id;
    delete ret.__v;
};

var donatedListSchema = new mongoose.Schema({
    tech_id: Number,
    donated_list: [unionDonatedItemSchema]
});

///////////////////////////////////////////////////////////
/**
 * 联盟任务系统
 */
var unionTaskSchema = new mongoose.Schema({
    // 角色id
    role_id: {
        type: Number,
        required: true,
        unique: true,
        index: true
    },

    // 当前任务列表
    unionTask_list: {
        type: [unionTaskItemSchema],
        default: _unionTask
    },

    // 已完成任务列表
    complete_task_list: [unionTaskItemSchema],

    // 声望
    total_reputation: {
        type: Number,
        default: 0
    },

    // 每日帮助获得声望
    daily_help_add_reputation: {
        type: Number,
        default: 0
    },

    // 每日声望
    max_reputation: {
        type: Number,
        default: 0
    },

    // 历史声望
    history_reputation_total: {
        type: Number,
        default: 0
    },

    // 每天任务次数
    union_task_num: {
        type: Number,
        default: constantUtil.value('union_mission_do_times')
    },

    // 正在进行的任务id
    start_task_id: {
        type: Number,
        default: 0
    },

    // 每天刷新任务次数
    refresh_num: {
        type: Number,
        default: constantUtil.value('union_mission_refresh_times')
    },

    // 任务次数(钻石刷新只有免费使用完才会开始记次)
    now_refresh_num: {
        type: Number,
        default: 0
    },

    // 任务次数(钻石刷新只有免费使用完才会开始记次)
    history_reputation: {
        type: Number,
        default: 0
    },

    // 已领取星级列表
    ok_receive_list: [Number],

    // 每日完成任务总星数
    total_star: {
        type: Number,
        default: 0
    },

    // // 联盟商城购买 次数
    // buy_shop_num: {
    //     type: Number,
    //     default: 0
    // },

    // 购买次数列表
    buy_num_list: {
        type: mongoose.Schema.Types.Mixed,
        default: {}
    },

    // 刷新商城次数
    refresh_shop_times: {
        type: Number,
        default: 0
    },

    // 捐赠
    donated_list: [donatedListSchema],

    // 联盟捐赠时间
    donated_time: {
        type: Number,
        default: _unionTime
    },
});

unionTaskSchema.pre('save', function (next) {
    this.increment();
    if (!this.isNew && !!this.isModified()) {
        this.pushModify();
    }
    next();
});

/**
 * 重置历史声望
 * * @return {[type]} [description]
 */
unionTaskSchema.methods.resHistory = function (value) {
    this.history_reputation_total = value;
};

/**
 * 重置冷却时间
 * @return {[type]} [description]
 */
unionTaskSchema.methods.restDonatedTime = function (time_num) {
    this.donated_time = moment().unix();
};

/**
 * 增加冷却时间
 * @return {[type]} [description]
 */
unionTaskSchema.methods.addDonatedTime = function (time_num) {
    var now_time = moment().unix();
    if (this.donated_time < now_time) {
        this.donated_time = now_time + time_num;
    } else {
        this.donated_time += time_num;
    }
};

/**
 * 增加捐赠
 * @return {[type]} [description]
 */
unionTaskSchema.methods.addDonatedList = function (tech_id) {
    var isVaild = true;
    _.some(this.donated_list, function (donated_item) {
        if (donated_item.tech_id == tech_id) {
            isVaild = false;
            return true;
        }
    });
    if (!!isVaild) {
        var donated_list = [];
        donated_list.push({
            donated_type: 1,
            reward_type: 1,
            reward_num: 5000,
            is_open: 1
        }, {
            donated_type: 2,
            reward_type: 0,
            reward_num: 0
        }, {
            donated_type: 3,
            reward_type: 0,
            reward_num: 0
        });
        this.donated_list.push({
            tech_id: tech_id,
            donated_list: donated_list
        });
    }
};

/**
 * 修改捐赠
 * @return {[type]} [description]
 */
unionTaskSchema.methods.setDonatedList = function (tech_id, donated_type, is_open, reward_type, reward_num) {
    var item_modify = null;
    this.addDonatedList(tech_id);
    _.some(this.donated_list, function (donated_item) {
        if (donated_item.tech_id == tech_id) {
            _.some(donated_item.donated_list, function (item) {
                if (item.donated_type == donated_type) {
                    item.is_open = is_open;
                    item.reward_num = reward_num;
                    item.reward_type = reward_type;
                    item_modify = item;
                }
            });
            return true;
        }
    });
    return item_modify;
};

/**
 * 获取捐赠状态
 * @return {[type]} [description]
 */
unionTaskSchema.methods.getDonatedList = function (tech_id) {
    var donated_list = [];
    _.some(this.donated_list, function (donated_item) {
        if (donated_item.tech_id == tech_id) {
            donated_list = donated_item;
            return true;
        }
    });
    return donated_list.donated_list || [];
};

/**
 * 增加总声望
 * @return {[type]} [description]
 */
unionTaskSchema.methods.addTotalReputation = function (num) {
    this.total_reputation += (+num);

    // 历史声望
    this.history_reputation_total += (+num);
};

/**
 * 帮助加声望
 * @return {[type]} [description]
 */
unionTaskSchema.methods.helpAddReputation = function (num) {
    num = +num;
    var union_help_reputation_limit = constantUtil.value('union_help_reputation_limit');
    if (this.daily_help_add_reputation >= union_help_reputation_limit) {
        return;
    }

    if (this.daily_help_add_reputation + num > union_help_reputation_limit) {
        num = union_help_reputation_limit - this.daily_help_add_reputation;
    }
    this.daily_help_add_reputation += num;
};

/**
 * 是否开启
 * @return {[type]} [description]
 */
unionTaskSchema.methods.isDonated = function (tech_id, donated_type) {
    var donated_item1 = null;
    var is_vaild = false;
    this.addDonatedList(tech_id);
    var list = this.getDonatedList(tech_id) || [];
    _.some(list, function (item) {
        if (item.donated_type == donated_type) {
            donated_item1 = item;
        }
    });
    return donated_item1;
};

/**
 * 增加捐赠
 * @return {[type]} [description]
 */
unionTaskSchema.methods.addDonated = function (donated_type, reward_type, reward_num) {
    var isVaild = true;
    _.some(this.donated_list, function (item) {
        if (item.donated_type == donated_type) {
            isVaild = false;
            return true;
        }
    });

    if (!!isVaild) {
        this.donated_list.push({
            donated_type: donated_type,
            reward_type: reward_type,
            reward_num: reward_num
        });
    }

};

/**
 * 移除捐赠
 * @return {[type]} [description]
 */
unionTaskSchema.methods.removeDonated = function (donated_type) {
    _.some(this.donated_list, function (item) {
        if (item.donated_type == donated_type) {
            item.remove();
            return true;
        }
    });
};

/**
 * 获取已购买type 次数
 * @return {[type]} [description]
 */
unionTaskSchema.methods.getBuyShopNum = function (shop_id) {
    return this.buy_num_list[shop_id] || 0;
};

/**
 * 获取已购买type 次数
 * @return {[type]} [description]
 */
unionTaskSchema.methods.getBuyShopNum = function (num) {
    this.max_reputation += num;
};

/**
 * 增加已购买type
 * @return {[type]} [description]
 */
unionTaskSchema.methods.addBuyShopNum = function (shop_id) {
    this.buy_num_list[shop_id] = this.buy_num_list[shop_id] || 0;
    this.buy_num_list[shop_id]++;
    this.markModified('buy_num_list');
};

/**
 * 设定当前任务队列
 * @return {[type]} [description]
 */
unionTaskSchema.methods.setQueue = function (task_id) {
    this.start_task_id = task_id;
};

/**
 * 扣除免费任务刷新次数
 * @return {[type]} [description]
 */
unionTaskSchema.methods.subFreeRefreshNum = function () {
    this.refresh_num--;
};

/**
 * 增加任务刷新次数
 * @return {[type]} [description]
 */
unionTaskSchema.methods.addDiamondRefreshNum = function () {
    this.now_refresh_num++;
};

/**
 * 任务加速设定
 * @return {[type]} [description]
 */
unionTaskSchema.methods.quickTaskConsume = function (task_id, quick_time) {
    _.some(this.unionTask_list, function (item) {
        if (item.task_id == task_id) {
            item.end_time -= quick_time;
            return true;
        }
    });
};

/**
 * 增加星数领取记录
 * @return {[type]} [description]
 */
unionTaskSchema.methods.addStarRecord = function (star_num) {
    var state = _.indexOf(this.ok_receive_list, star_num) == -1;
    if (!!state) {
        this.ok_receive_list.push(star_num);
        return true;
    } else {
        return false;
    }
};

/**
 * 手动刷新商城
 */
unionTaskSchema.methods.manulRefreshShop = function () {
    var self = this;

    var union_shop_refresh_times_limit = constantUtil.value('union_shop_refresh_times_limit');
    if (self.refresh_shop_times >= union_shop_refresh_times_limit) {
        return false;
    }

    self.refresh_shop_times++;
    self.buy_num_list = {};
    return true;
};

/**
 * 每日刷新
 * @return {[type]} [description]
 */
unionTaskSchema.methods.refresh = function (reputation_num) {
    this.total_star = 0;
    this.daily_help_add_reputation = 0;
    this.refresh_num = constantUtil.value('union_mission_refresh_times');
    this.union_task_num = constantUtil.value('union_mission_do_times');
    this.complete_task_list = [];
    this.ok_receive_list = [];
    var state = this.start_task_id;
    this.max_reputation = 0;
    this.buy_num_list = {};
    this.refresh_shop_times = 0;
    if (!state) {
        this.refreshTask();
    }
};

/**
 * 增加声望
 * @return {[type]} [description]
 */
unionTaskSchema.methods.addReputation = function (reputation_num) {
    var max_reputation = constantUtil.value('union_help_reputation_limit');

    if (this.max_reputation + reputation_num > max_reputation) {
        this.max_reputation = max_reputation;
    } else {
        this.total_reputation += reputation_num;
        this.history_reputation_total += reputation_num;
        this.max_reputation += reputation_num;
    }
};

/**
 * 消耗声望
 * @return {[type]} [description]
 */
unionTaskSchema.methods.subReputation = function (reputation_num) {
    if (this.total_reputation >= reputation_num) {
        this.total_reputation -= reputation_num;
        return true;
    } else {
        return false;
    }
};

/**
 * 增加星级
 * @return {[type]} [description]
 */
unionTaskSchema.methods.addStar = function (star_num) {
    this.total_star += star_num;
};

/**
 * 获取上次刷新时间
 * @return {[type]} [description]
 */
unionTaskSchema.methods.getTotalStar = function () {
    return this.total_star;
};

/**
 * 任务次数--
 * @return {[type]} [description]
 */
unionTaskSchema.methods.addTaskNum = function () {
    if (this.union_task_num > 0) {
        this.union_task_num--;
    } else {
        this.union_task_num = 0;
    }
};

/**
 * 刷新次数++
 * @return {[type]} [description]
 */
unionTaskSchema.methods.addRefreshNum = function () {
    this.refresh_num++;
};

/**
 * 重置联盟任务
 * @return {[type]} [description]
 */
unionTaskSchema.methods.refreshTask = function () {
    var self = this;
    self.unionTask_list = [];
    var task_list = unionMissionConf.randomReward();

    _.each(task_list, function (item) {
        self.unionTask_list.push({
            task_id: item.id,
            cost_time: item.cost_time,
            end_time: 0,
            star: item.star,
            reputation: item.reputation
        });
    });
};

/**
 * 联盟任务刷新(如果任务不在进行中移除任务)
 * @return {[type]} [description]
 */
unionTaskSchema.methods.taskRefresh = function () {
    var self = this;
    var old_start_item = {};
    var isVaild = false;

    // 移除不在进行中的任务
    _.some(self.unionTask_list, function (start_item) {
        if (start_item.end_time) {
            old_start_item = start_item;
            isVaild = true;
            return true;
        }
    });

    self.unionTask_list = [];
    if (!!isVaild) {
        self.unionTask_list.push(old_start_item);
    }

    // 补充剩余任务
    var task_list = unionMissionConf.randomReward();
    var is_task_id = old_start_item.task_id || 999999;
    _.each(task_list, function (task_list_item) {
        if (task_list_item.id !== is_task_id && self.unionTask_list.length < 3) {
            self.unionTask_list.push({
                task_id: task_list_item.id,
                cost_time: task_list_item.cost_time,
                end_time: 0,
                star: task_list_item.star,
                reputation: task_list_item.reputation
            });
        }
    });
};

// 任务都完成后重置
unionTaskSchema.methods.setTaskRefresh = function () {
    var self = this;

    if (self.unionTask_list.length > 0) {
        self.unionTask_list = [];
    }

    var task_list = unionMissionConf.randomReward();

    _.each(task_list, function (task_list_item) {
        self.unionTask_list.push({
            task_id: task_list_item.id,
            cost_time: task_list_item.cost_time,
            end_time: 0,
            star: task_list_item.star,
            reputation: task_list_item.reputation
        });
    });
};

/**
 * 任务是否完成(如果完成---移到完成任务列表，并从当前列表中移除)
 * @return {[type]} [description]
 */

// 移除操作
unionTaskSchema.methods.isTaskReceive = function (task_id) {
    var self = this;
    var isVaild = false;
    var now_time = moment().unix();
    _.some(this.unionTask_list, function (item) {
        if (item.task_id == task_id) {

            if (item.end_time > 0 && item.end_time < now_time) {
                self.complete_task_list.push(item);
                item.remove();
                isVaild = true;
                return true;
            }
        }
    });
    return isVaild;
};

unionTaskSchema.methods.removeTask = function (item) {
    _.some(this.unionTask_list, function (item_now) {
        if (item_now.task_id == item.task_id) {
            item_now.remove();
            return true;
        }
    });
};

// 加入操作
unionTaskSchema.methods.isTaskReceiveTwo = function (task_id) {
    var self = this;
    var isVaild = false;
    var task_item = null;
    var now_time = moment().unix();

    _.some(this.unionTask_list, function (item) {
        if (item.task_id == task_id) {
            if (item.end_time > now_time) {
                task_item = item;
                isVaild = true;
                return true;
            }
        }
    });
    return task_item;
};

// 读取操作
unionTaskSchema.methods.isTaskReceiveTree = function (task_id) {
    var self = this;
    var isVaild = false;
    var task_item;
    var now_time = moment().unix();
    _.some(this.unionTask_list, function (item) {
        if (item.task_id == task_id) {
            task_item = item;
            isVaild = true;
            return true;
        }
    });
    return task_item || null;
};

/**
 * 任务是否进行中
 * @return {[type]} [description]
 */
unionTaskSchema.methods.isTaskStart = function (task_id) {
    var isVaild = false;
    _.some(this.unionTask_list, function (item) {
        if (item.task_id == task_id) {
            if (item.end_time !== 0) {
                isVaild = true;
                return true;
            }
        }
    });
    return isVaild;
};

/**
 * 任务是否存在
 * @return {[type]} [description]
 */
unionTaskSchema.methods.isUnionTask = function (task_id) {
    var union_task_item;
    _.some(this.unionTask_list, function (item) {
        if (item.task_id == task_id) {
            item.end_time = moment().unix() + item.cost_time;
            union_task_item = item;
            return true;
        }
    });
    return union_task_item;
};

/**
 * 获取修改
 * @return {[type]} [description]
 */
unionTaskSchema.methods.getLastChange = function () {
    return this.toJSON();
};

/**
 * 推送给用户
 * @return {[type]} [description]
 */
unionTaskSchema.methods.push = function () {
    this.pushModify();
};

unionTaskSchema.methods.pushModify = function () {
    unionTaskMgr.sendUnionTaskChanged(
        this.role_id,
        this.getLastChange(),
        function (err, fails) {
            if (err) {
                console.error('send vip message error: %j, fail ids: %j', err, fails);
                return;
            }
        }
    );
};

if (!unionTaskSchema.options.toJSON) {
    unionTaskSchema.options.toJSON = {};
}
/* jshint unused:false */
unionTaskSchema.options.toJSON.transform = function (doc, ret) {
    delete ret.complete_task_list;
    delete ret._id;
    delete ret.__v;
};

mongoose.model('UnionTask', unionTaskSchema);
